package com.eunion.web.cms.controller;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eunion.common.util.RegUtils;
import com.eunion.core.ExcelUtil;
import com.eunion.core.LogUtil;
import com.eunion.core.exception.ValidateException;
import com.eunion.fileserver.upload.FileInfo;
import com.eunion.web.cms.entity.MajorRecruitPlan;
import com.eunion.web.cms.entity.RecruitStudentsPlan;
import com.eunion.web.cms.entity.ScoreRank;
import com.eunion.web.cms.entity.spec.MajorStudentsPlanSpec;
import com.eunion.web.cms.service.MajorRecruitPlanService;
import com.eunion.web.common.base.BaseService;
import com.eunion.web.common.base.BaseTableCommonController;

/**
 * 专业招生计划
 * @author changzuzhe
 *
 */
@Controller
@PreAuthorize("hasAuthority('majorrecruitplan:info')")
@RequestMapping("/api/major-recruit-plan")
public class MajorRecruitPlanResource  extends BaseTableCommonController<MajorRecruitPlan, Long>  {

    @Autowired
    private MajorRecruitPlanService service;

    @Override
    protected BaseService<MajorRecruitPlan, Long> getBaseService() {
        // TODO Auto-generated method stub
        return service;
    }
    
    @RequestMapping("/index")
    public String index() {
        return getUrlBase();
    }

    @Override
    protected String getUrlBase() {
        return "admin/majorrecruitplan/majorrecruitplan";
    }
    
    @PreAuthorize("hasAuthority('majorrecruitplan:import')")
    @PostMapping("/importData")
    public String importData(FileInfo obj, BindingResult result, Model model, HttpServletRequest request) {
        try {
            checkBindResult(result);
            if (StringUtils.isNotBlank(obj.getFilepath())) {
                String filepath = obj.getFilepath();
                String fileType = filepath.substring(filepath.lastIndexOf(".") + 1);
                InputStream in = null;

                Workbook wb = null;
                if (fileType.equals("xls")) {
                    in = new FileInputStream(filepath);
                    wb = new HSSFWorkbook(in);
                } else if (fileType.equals("xlsx")) {
                    in = new FileInputStream(filepath);
                    wb = new XSSFWorkbook(in);
                } else {
                    setModuleStatusError(model, "文件格式错误");
                    setModuleImport(model);
                    return getUrlBase().concat("-import");
                }

                // 上传文件的原始名称
                String fileNameOrg = obj.getFileNameOrg();
               /* // 方向，1.文科，2.理科
                int direction = 0;
                if (StringUtils.isNotBlank(fileNameOrg)) {
                    if (fileNameOrg.contains("文科")) {
                        direction= 1;
                    } else if (fileNameOrg.contains("理科")) {
                        direction= 2;
                    }
                }
                // 年份
                String year = RegUtils.getNumbers(fileNameOrg);
                // 省份
                String provinceName = fileNameOrg.split("_")[1].replace("省", "").replace("市", "");*/
                
                // 开始解析数据
                Sheet sheet = wb.getSheetAt(0);
                List<MajorRecruitPlan> list = ExcelUtil.readMajorRecruitPlan(sheet, fileNameOrg);

                boolean ret = importUpdate(list);
                if(ret) {
                    setModuleStatusOK(model, "导入成功");
                } else {
                    LogUtil.get(this.getClass()).error("save recruitStudentsPlanList failed");
                    setModuleStatusOK(model, "导入失败");
                }
            }
        } catch (ValidateException ve) {
            setModuleStatusError(model, ve.getMsg());
        } catch (Exception e) {
            LogUtil.get(this.getClass()).error("save obj error : {}", e);
            setModuleStatusError(model, "导入失败");
        }
        setModuleImport(model);
        return getUrlBase().concat("-import");
    }
    
    
    protected void update(MajorRecruitPlan fromDB,MajorRecruitPlan fromFile) {
        fromFile.setId(fromDB.getId());
    }

    protected Specification<MajorRecruitPlan> getSpecification(MajorRecruitPlan t){
        return MajorStudentsPlanSpec.build(t,true);
    }
}
